package homework4.action_e;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import homework4.Bean.Book;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author CoderXshuai
 */
public class BookAction extends ActionSupport implements ModelDriven {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private Book books = new Book();
    private ArrayList<Book> book_list;
    private static final SessionFactory FACTORY;
    private String key;
    private Date minvalue;
    private Date maxvalue;

    static {
        //加载核心配置文件
        Configuration configuration = new Configuration();
        configuration.configure();
        //创建SessionFactory对象，并在数据库中把表创建出来
        FACTORY = configuration.buildSessionFactory();
    }

    final Session session = getSession();
    private int id;

    public static Session getSession() {
        return FACTORY.openSession();
    }

    public Date getMinvalue() {
        return minvalue;
    }

    public void setMinvalue(Date minvalue) {
        try {
            minvalue = sdf.parse("2019-01-01");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public Date getMaxvalue() {
        return maxvalue;
    }

    public void setMaxvalue(Date maxvalue) {
        try {
            maxvalue = sdf.parse("2019-12-01");
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public Object getModel() {
        // TODO Auto-generated method stub
        return books;
    }

    public String Add() {
        try {
            final Session session = getSession();
            Query query = session.createQuery("from Book ");
            List list = query.getResultList();
            book_list = new ArrayList<>();
            book_list = (ArrayList<Book>) list;
            session.save(books);
            session.beginTransaction().commit();
            return SUCCESS;
        } catch (Exception exp) {
            return ERROR;
        }

    }

    public String search() {
        book_list = (ArrayList<Book>) ServletActionContext.getServletContext().getAttribute("booklist");
        return SUCCESS;
    }

    public String Get() {
        try {
//            String id_tmp = ServletActionContext.getRequest().getParameter("id");
//            if (id_tmp != null && id_tmp != "") {
//                int id = Integer.parseInt(id_tmp);
//                if (ServletActionContext.getServletContext().getAttribute("booklist") != null) {
//                    book_list = (ArrayList<Book>) ServletActionContext.getServletContext().getAttribute("booklist");
//                    books = book_list.get(id);
//                    return "editindex";
//                } else {
//                    return ERROR;
//                }
//            }
            Query query = session.createQuery("from Book ");
            List list = query.getResultList();
            book_list = new ArrayList<>();
            book_list = (ArrayList<Book>) list;
            System.out.println(book_list.get(0).getBookName());
            session.beginTransaction().commit();
            id = 5;
            return "editindex";
//            else {
//                return ERROR;
//            }
        } catch (Exception exp) {
            return ERROR;
        }
    }

    public Book getBooks() {
        return books;
    }

    public void setBooks(Book books) {
        this.books = books;
    }

    public ArrayList<Book> getBook_list() {
        return book_list;
    }

    public void setBook_list(ArrayList<Book> book_list) {
        this.book_list = book_list;
    }

    public String Edit() {
        try {
            final Session session = getSession();
            session.save(books);
            session.beginTransaction().commit();

            return SUCCESS;
        } catch (
                Exception exp) {
            return ERROR;
        }

    }

    public String Delete() {
        try {
            String id_tmp = ServletActionContext.getRequest().getParameter("id");
            if (id_tmp != null && id_tmp != "") {
                int id = Integer.parseInt(id_tmp);
                if (ServletActionContext.getServletContext().getAttribute("booklist") != null) {
                    book_list = (ArrayList<Book>) ServletActionContext.getServletContext().getAttribute("booklist");
                    books = book_list.get(id);
                    books.setFlag(0);
                    book_list.set(id, books);
                    ServletActionContext.getServletContext().setAttribute("booklist", book_list);
                    return SUCCESS;
                } else {
                    return ERROR;
                }
            } else {
                return ERROR;
            }
        } catch (Exception exp) {
            return ERROR;
        }
    }

    public void validateAdd() {
//        if (books.getPress().indexOf("出版社") == -1) {
//            addFieldError("press", "出版社名称必须包含出版社");
//        }
        // 要求用户名必须包含.
        String s = checkISBN(books.getISBN());
        if (s != "" && s != "error") {
            addFieldError("ISBN", s);
        }
    }

    public String checkISBN(String isbn) {
        int count = 0;
        int checkBitInt = 0;
        char[] cs = isbn.toCharArray();
        if (!isbn.startsWith("978") && !isbn.startsWith("979")) {
            return "ISBN-13 格式不符合标准";
        }
        // 取出前12位数字进行加权和计算
        int countEven = 0;
        int countOdd = 0;
        for (int i = 0; i < 12; i++) {
            int c = cs[i] - '0';
            // 若前12位数据中有非数字字符，则抛出异常
            if (c < 0 || c > 9) {
                return ("ISBN " + isbn + " 第 " + (i + 1) + " 位中出现非法字符 " + cs[i]);
            }
            // 分别计算奇位数和偶位数的和
            if ((i & 0x1) == 0) {
                countOdd += c;
            } else {
                countEven += c;
            }
        }
        // 求加权和
        count = countOdd + (countEven * 3);

        // 取出校验位数据
        if (cs[12] < '0' || cs[12] > '9') {
            // 校验位为非0~9字符时，抛出异常
            return ("ISBN " + isbn + " 第 13 位中出现非法字符 " + cs[12]);
        }

        checkBitInt = cs[12] - '0';
        // 进行校验
        if ((count + checkBitInt) % 10 == 0) {
            return ""; // 校验成功
        } else {
            return "error"; // 校验失败
        }

    }

    @Override
    public String execute() throws Exception {
        id = 5;
        return SUCCESS;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}